<?php

namespace app\home\controller;



use think\facade\Cache;

class Cart extends Base
{
    //加入购物车  表单提交
    public function addcart()
    {
        if(request()->isGet()){
            //如果是get请求 跳转到首页
            return redirect('/index/index');
        }

        //接收数据
        $params = input();

        //参数检测
        $validate = $this->validate($params, [
            'goods_id' => 'require|integer|gt:0',
            'number' => 'require|integer|gt:0',
            'spec_goods_id' => 'integer|gt:0',
        ]);
        if($validate !== true){
            $this->error($validate);
        }
        //处理数据 调用封装好的方法
//        \app\home\logic\CartLogic::addCart($params['goods_id'], $params['spec_goods_id'], $params['number']);
        $user = session('user_info');
        $userId = $user['id'];
        $spec_goods_id = $params['spec_goods_id'];
        $goodsId = $params['goods_id'];

        $cartData = Cache::store('redisCart')->hGet(config('redis.cart_user').$userId,$spec_goods_id);
        if($cartData){
            $cartData = json_decode($cartData,true);
            $params['number'] = $cartData['number'] + $params['number'];
        }
        Cache::store('redisCart')->multi()
            ->hSet(config('redis.cart_user').$userId,$spec_goods_id,json_encode($params))
            ->sAdd(config('redis.cart_selected').$userId,$spec_goods_id)
            ->exec();
//        Cache::store('redisCart')->hSet(config('redis.cart_user').$userId,$spec_goods_id,json_encode($params));
//        Cache::store('redisCart')->sAdd(config('redis.cart_selected').$userId,$spec_goods_id);
        //结果页面展示
        //查询商品相关信息以及SKU信息
        $goods = \app\common\model\mysql\Goods::getGoodsWithSpec($spec_goods_id, $goodsId);
        return view('addcart', ['goods' => $goods, 'number' => $params['number']]);
    }

    public function index()
    {
        //查询所有的购物记录
//        $list = \app\home\logic\CartLogic::getAllCart();
        $user = session('user_info');
        $list = Cache::store('redisCart')->hGetAll(config('redis.cart_user').$user['id']);
        $selected = Cache::store('redisCart')->sMembers(config('redis.cart_selected').$user['id']);
        if(!empty($list) && !empty($selected)){
            foreach(array_values($list) as $value){
                $lis[] = json_decode($value,true);
            }

            //对每一条购物记录 查询商品相关信息（商品信息和SKU信息）
            foreach($lis as &$v){
                //$v['goods_id']  $v['spec_goods_id']
                $v['goods'] = \app\common\model\mysql\Goods::getGoodsWithSpec($v['spec_goods_id'], $v['goods_id'])->toArray();
                if(in_array($v['spec_goods_id'],$selected)){
                    $v['is_selected'] = 1;
                }else{
                    $v['is_selected'] = 0;
                }
            }
            unset($v);
        }else{
            $lis = [];
        }






        return view('index', ['list' => $lis]);
    }

    /**
     * ajax修改购买数量
     */
    public function changenum()
    {
        //接收参数  id  number
        $params = input();
        //参数检测
        $validate = $this->validate($params, [
            'id' => 'require',
            'number' => 'require|integer|gt:0'
        ]);
        if($validate !== true){
            $res = ['code' => 400, 'msg' => '参数错误'];
            echo json_encode($res);die;
        }
        //处理数据
//        \app\home\logic\CartLogic::changeNum($params['id'], $params['number']);
        $cartData = Cache::store('redisCart')->hGet(config('redis.cart_user').$this->userId,$params['id']);
        if($cartData){
            $cartData = json_decode($cartData,true);
            $cartData['number'] =  $params['number'];
        }
        Cache::store('redisCart')->hSet(config('redis.cart_user').$this->userId,$params['id'],json_encode($cartData));
        //返回数据
        $res = ['code' => 200, 'msg' => 'success'];
        echo json_encode($res);die;
    }

    /**
     * ajax删除购物记录
     */
    public function delcart()
    {
        //接收参数
        $params = input();
        //参数检测
        /*$validate = $this->validate($params, [
            'id' => 'require'
        ]);
        if($validate !== true){
            $res = ['code' => 400, 'msg' => $validate];
            echo json_encode($res);die;
        }*/

        if(!isset($params['id']) || empty($params['id'])){
            $res = ['code' => 400, 'msg' => '参数错误'];
            echo json_encode($res);die;
        }

        //处理数据
//        \app\home\logic\CartLogic::delCart($params['id']);
        Cache::store('redisCart')->hDel(config('redis.cart_user').$this->userId,$params['id']);
        Cache::store('redisCart')->sRem(config('redis.cart_selected').$this->userId,$params['id']);
        //返回数据
        $res = ['code' => 200, 'msg' => 'success'];
        echo json_encode($res);die;
    }

    /**
     * ajax修改选中状态
     */
    public function changestatus()
    {
        //接收参数
        $params = input();

        //参数检测
        $validate = $this->validate($params, [
            'id' => 'require',
            'status' => 'require|in:0,1'
        ]);
        if($validate !== true){
            $res = ['code' => 400, 'msg' => $validate];
            echo json_encode($res);die;
        }
        $cacheObj = Cache::store('redisCart');

        if($params['id'] == 'all'){

                foreach($params['all_ids'] as $v){
                    if($params['status']){
                        $cacheObj->sAdd(config('redis.cart_selected').$this->userId,$v);
                    }else{
                        $cacheObj->sRem(config('redis.cart_selected').$this->userId,$v);
                    }



            }

        }else{
            //处理数据
//        \app\home\logic\CartLogic::changeStatus($params['id'], $params['status']);
            if(!$params['status']){
                $cacheObj->sRem(config('redis.cart_selected').$this->userId,$params['id']);
            }else{
                $cacheObj->sAdd(config('redis.cart_selected').$this->userId,$params['id']);
            }
        }

        //返回数据
        $res = ['code' => 200, 'msg' => 'success'];
        echo json_encode($res);die;
    }
}
